#include "ExtCleaner.h"

ExtCleaner::ExtCleaner(void):
    _deleted(0)
{
}

ExtCleaner::ExtCleaner(const std::string & path):
    _iter( new Poco::DirectoryIterator(path) ),
    _deleted(0)
{
}

ExtCleaner::ExtCleaner(const Poco::DirectoryIterator & iterator):
    _iter( new Poco::DirectoryIterator(iterator) ),
    _deleted(0)
{
}

ExtCleaner::ExtCleaner(const Poco::File & file):
    _iter( new Poco::DirectoryIterator(file) ),
    _deleted(0)
{
}

ExtCleaner::ExtCleaner(const Poco::Path & path):
    _iter( new Poco::DirectoryIterator(path) ),
    _deleted(0)
{
}

ExtCleaner::~ExtCleaner(void)
{
}

Poco::Path ExtCleaner::getCurPath() const
{
    return _iter->path();
}

std::string ExtCleaner::getCurFileName() const
{
    return _iter->name();
}

int ExtCleaner::addExt(const std::string & ext)
{
    size_t size = _exts.size();
    int i;
    
    for(i = 0; i < size; i++) {
        if(_exts[i] == ext) {
            return 1;
        }
    }

    _exts.push_back(ext);

    return 0;
}

int ExtCleaner::remExt(const std::string & ext)
{
    std::vector<std::string>::iterator iter;

    for(iter = _exts.begin(); iter != _exts.end(); iter++) {
        if(*iter == ext) {
            _exts.erase(iter);
            
            return 0;
        }
    }

    return 1;
}

std::vector<std::string> ExtCleaner::getExt() const
{
    return _exts;
}

int ExtCleaner::doRemove()
{
    if( _exts.empty() ) {
        return 1;
    }

    std::string ext;
    std::vector<std::string>::iterator iter, begin, end;
    begin = _exts.begin();
    end = _exts.end();
    
    _dirs.push_back( _iter->path().parent().toString() );

    while( _dirs.size() ) {
        _iter = new Poco::DirectoryIterator( _dirs[0] );

        while( _iter->path().getFileName() != "" ) {
            if( (*(*_iter)).isFile() ) {
                ext = _iter->path().getExtension();
                for(iter = begin; iter != end; iter++) {
                    if(*iter == ext) {
                        try {
                            (*(*_iter)).remove();
                            _deleted++;
                        } catch(...) {
                        }
                    }
                }
            } else if( (*(*_iter)).isDirectory() ) {
                _dirs.push_back( _iter->path().toString() );
            }

            (*_iter)++;
        }

        _dirs.erase( _dirs.begin() );
    }

    return 0;
}

int ExtCleaner::getDeleted() const
{
    return _deleted;
}
